/**
 * 
 */
package com.cnhaimei.vod.logic;

import java.util.ArrayList;
import java.util.HashMap;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.util.SparseArray;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnKeyListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.TextView;

import com.cnhaimei.com.HListView;
import com.cnhaimei.com.VODLog;
import com.cnhaimei.com.HListView.MyTouchListner;
import com.cnhaimei.com.PageManager;
import com.cnhaimei.com.PageManager.PageInfoListener;
import com.cnhaimei.com.SearchTextView;
import com.cnhaimei.com.widget.ViewFlow;
import com.cnhaimei.com.widget.ViewFlow.ViewSwitchListener;
import com.cnhaimei.vod.FavoriteManager;
import com.cnhaimei.vod.FavoriteManager.OperateResultType;
import com.cnhaimei.vod.R;
import com.cnhaimei.vod.SelSongsManager;
import com.cnhaimei.vod.bean.Singer;
import com.cnhaimei.vod.bean.Song;
import com.cnhaimei.vod.logic.EventsManager.EventsListener;
import com.cnhaimei.vod.net.NetManager;
import com.cnhaimei.vod.net.Request;
import com.cnhaimei.vod.net.XVod;
import com.cnhaimei.vod.net.dc.Player;
import com.cnhaimei.vod.net.dq.DQClose;
import com.cnhaimei.vod.net.dq.DQQuery;
import com.cnhaimei.vod.net.dq.DQQueryResult;
import com.cnhaimei.vod.net.dq.DQRead;
import com.cnhaimei.vod.net.dq.DQReadResult;
import com.cnhaimei.vod.net.dq.DQSinger;
import com.cnhaimei.vod.net.dq.DQSongs;
import com.cnhaimei.vod.net.dq.SingerParser;
import com.cnhaimei.vod.net.dq.SongParser;
import com.cnhaimei.vod.util.Const;
import com.cnhaimei.vod.util.Const.QueryType;
import com.cnhaimei.vod.util.ImageLoader;
import com.cnhaimei.vod.util.Util;

/**
 * 明星专辑
 * 
 * @author Jin001.Wu@gmail.com <br>
 * @date 2011-7-4
 * 
 */
public class StarSongsActivity extends VODActivity implements
		PageInfoListener,MyTouchListner, TextWatcher, ViewSwitchListener {
	public final static String EXTRA_KEY_NAME = "singer_name"; 
	private static final int PAGE_SIZE = 7;
	//private HListView listView;
	private ViewFlow listView;	
	private TextView curPageView;
	private TextView totalPageView;
	private TextView imageView; // 头像
	private TextView starView;

	private LayoutInflater mInflater;
	private AdapterEx mListAdapter;
	private PageManager pageManager;
	private SparseArray<ArrayList<Song>> mPageCache = new SparseArray<ArrayList<Song>>();
//	private DQQueryResult queryResult;
//	private SongParser songParser;
//	private Singer singer;
	private ArrayList<Song> curSongList;

	private View curSelView;
//	private long curSearchId;
	private HashMap<Long, Integer> pageSongReq = new HashMap<Long, Integer>();
	private Search mSearch;
	private Singer mSinger;
	private String singerName;
	private String starName;//原始歌星名（用于查询）
	
	private View mSelSongView;//更多菜单选中的项，用于onActivityResult时selectItem用


	private View mHeadView;
	private SearchTextView mSearchView;
	private View mCancelView;
	private boolean mSearchViewFocused = false;
	
	private int mQueryType = QueryType.COMMON;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.v8_star_songs);
		showBackBtn(true);
		
		setClickable(R.id.pre_page, R.id.next_page);//, R.id.goback, R.id.close);

		mInflater = LayoutInflater.from(this);
//		singer = SingerListActivity.selSinger;
		singerName = getIntent().getStringExtra(EXTRA_KEY_NAME).trim();
		mQueryType = getIntent().getIntExtra(Const.Key.QUERY_TYPE, QueryType.COMMON);
		
		if (singerName != null) {
			if (singerName.indexOf('|') == 0) {
				singerName = singerName.substring(1);
			}
			if (singerName.lastIndexOf('|') == singerName.length() - 1) {
				singerName = singerName.substring(0, singerName.length() - 1);
			}
			starName = singerName;
			
			singerName = singerName.replace("|", " ");
			singerName = singerName.trim();
			setTitle(singerName);
		}
		
		if (Util.DEMO) {
			curSongList = new ArrayList<Song>(42);
			for (int i = 1; i < 3; i++) {
				for (int j = 1; j < 4; j++) {
					curSongList.add(Song.createSong("寒江雪" + (i * 100 + j), "郑源"
							+ (i * 100 + j), "高清"));
				}
			}
		}

		initView();
		

		if (mCancelView != null) {
			mCancelView.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if (mSearchView != null) {
						mSearchView.clearFocus();
						mCancelView.setVisibility(View.GONE);
						mHeadView.setVisibility(View.VISIBLE);
						mSearchView.setText("");
					}					

					if (mSearch != null) {
						mSearch.searchSongs(null);
					}
				}
			});
		}
		if (mSearchView != null) {

			mSearchView.addTextChangedListener(this);//监听输入变化
			
			mSearchView.setOnFocusChangeListener(new OnFocusChangeListener() {
				
				@Override
				public void onFocusChange(View v, boolean hasFocus) {
					// TODO Auto-generated method stub
					mSearchViewFocused = hasFocus;
				}
			});
			mSearchView.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
//					if (mSearchViewFocused) {
//						mCancelView.setVisibility(View.VISIBLE);
//						mHeadView.setVisibility(View.GONE);
//					}
				}
			});
			mSearchView.setOnKeyListener(new OnKeyListener() {
				
				@Override
				public boolean onKey(View v, int keyCode, KeyEvent event) {
					// TODO Auto-generated method stub
					if(event.getAction() == KeyEvent.ACTION_UP && keyCode==KeyEvent.KEYCODE_ENTER){//修改回车键功能
						String search = mSearchView.getText().toString();
						search = search.trim();
						//if (search.length() > 0) 
						{
							
							// 先隐藏键盘
							((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(
											StarSongsActivity.this
											.getCurrentFocus()
											.getWindowToken(),
											InputMethodManager.HIDE_NOT_ALWAYS);

							if (mSearch != null) {
								mSearch.searchSongs(search);
							}
						}
					}
				
					return false;					
				}
			});
		}
		
		mSearch = new Search();
		mSearch.regesiterEventsListener();

		pageManager = new PageManager();
		pageManager.setPageButtonView(findViewById(R.id.pre_page),
				findViewById(R.id.next_page), null, null);
		if (Util.DEMO) {
			pageManager.setPageInfo(100, 999, false);
		}
		pageManager.setListener(this);

		refreshPage();
		
		if (starName != null) {
			mSearch.search(starName);
//			curSearchId = XVod.G().searSingerSong();
		}
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		if (isFinishing()) {
//			pageSongReq.clear();// 不要clear,可能网络上数据还未返回
			mSearch.unRegisterEventsListener();
			mTaskListener.unListener();
		}
	}
	
	private void initView() {
		imageView = (TextView) findViewById(R.id.image);
		listView = (ViewFlow) findViewById(R.id.viewflow);//findViewById(R.id.list);
		curPageView = (TextView) findViewById(R.id.cur_page);
		totalPageView = (TextView) findViewById(R.id.total_page);
		starView = (TextView)findViewById(R.id.name);

		mSearchView = (SearchTextView) findViewById(R.id.search_edit);
		mCancelView = findViewById(R.id.cancel_btn);
		mHeadView = findViewById(R.id.head);
		
		if (listView != null) {
			listView.setOnViewSwitchListener(this);
		}
	}
	
	public void refreshSingerInfo() {
		if (mSinger != null) {
			/*
			Bitmap b = ImageLoader.G.getBitmap(mTaskListener, mSinger
					.getImgName());
			if (b != null) {
				imageView.setBackgroundDrawable(new BitmapDrawable(b));
			} else {
				imageView.setBackgroundResource(R.drawable.default_star);
			}
			*/
			starView.setText(mSinger.getName());
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		Song tmpSong = null;
		if (data != null){
			tmpSong = (Song)data.getSerializableExtra(Const.Key.SONG_INFO);
			if (tmpSong == null) {
				return;
			}
		}
		if (requestCode == Const.RequestCode.SEL_SONG_MORE)
		{
			switch(resultCode)
			{
			case Const.ResultCode.SEL_SONG:
				XVod.G().insertSong(tmpSong);
				//showMyToast("点播歌曲成功");
				if (mSelSongView != null) {
					selectItem(mSelSongView);
				}
				break;
			case Const.ResultCode.INSERT_SONG:
				final Player p = Player.G();
				if (p.getPlaylistCount() < Player.MAX_SEL) {
					int count = p.getPlaylistCount();
					XVod.G().insertSong(tmpSong);
					XVod.G().preSortSong(count, 1); 
				}
				showMyToast("插播歌曲置顶成功");
				if (mSelSongView != null) {
					selectItem(mSelSongView);
				}
				break;
			case Const.ResultCode.SEL_SINGER:
				break;
			case Const.ResultCode.ADD_FAVORITE:
				OperateResultType type = FavoriteManager.G().addSong(tmpSong);
				if (type == OperateResultType.SUCCESS) {
					showMyToast("添加收藏成功！");
				} 
				else if (type == OperateResultType.EXIST_ALREADY) {
					showMyToast("已经收藏过该歌曲！");
				}
				break;
			}
		}
	}
	
	ImageLoader.ImageTaskListener mTaskListener = new ImageLoader.ImageTaskListener() {
		public void onLoadingFinished(Bitmap bitmap, String url) {
			if (bitmap != null) {
				imageView.setBackgroundDrawable(new BitmapDrawable(bitmap));
			} else {
				imageView.setBackgroundResource(R.drawable.default_star);
			}
		}
	};
	
	public static void starActivity(Context contex, String starName) {
		Intent i = new Intent(Const.Action.ShowStarsSongs);
		i.putExtra(StarSongsActivity.EXTRA_KEY_NAME, starName);
		contex.startActivity(i);
	}

	public void onClick(View v) {
		int id = v.getId();
		switch (id) {
		case R.id.pre_page:
			break;
		case R.id.next_page:
			break;
		case R.id.goback:
		case R.id.close:
			finish();
			break;
		default:
			super.onClick(v); // need parent
			break;
		}
	}

	private void refreshPage() {
		if (mListAdapter == null) {
			mListAdapter = new AdapterEx();
			listView.setAdapter(mListAdapter);
//			listView.setOnItemClickListener(mListAdapter);
//			listView.setOnItemSelectedListener(mListAdapter);
		}
		//mListAdapter.setList(curSongList);
		mListAdapter.notifyDataSetChanged();

		int total = pageManager.getTotalPage();
		curPageView.setText(getString(R.string.cur_page, pageManager
				.getCurrentIndex() + 1));
		totalPageView.setText(getString(R.string.total_page, total));
	}


	private void selectItem(View itemRoot) {
		if (curSelView == itemRoot) {
			return ;
		}
		curSelView = itemRoot;
		if (curSelView != null) {
			TextView nameView = (TextView)curSelView.findViewById(R.id.name);
			if (nameView != null) {
				nameView.setTextColor(getResources().getColor(R.color.blue_color));
			}
		}
	}

	private void unselectItem(View itemRoot) {
		if (itemRoot != null) {
			TextView nameView = (TextView)itemRoot.findViewById(R.id.name);
			if (nameView != null) {
				nameView.setTextColor(getResources().getColor(R.color.white_color));
			}
		}
	}
	
	/*
	private void selectItem(View itemRoot) {
		curSelView = itemRoot;
		if (curSelView != null) {
			ViewHolder holder = (ViewHolder) curSelView.getTag();
			
			if (holder != null && holder.name != null) {
				holder.name.setTextColor(getResources().getColor(R.color.blue_color));
			}
		}
	}

	private void unselectItem(View itemRoot) {
		curSelView = itemRoot;
		if (curSelView != null) {
			ViewHolder holder = (ViewHolder) curSelView.getTag();
			
			if (holder != null && holder.name != null) {
				holder.name.setTextColor(getResources().getColor(R.color.white_color));
			}
		}
	}
	
	public class AdapterEx extends BaseAdapter implements OnItemClickListener
	, OnClickListener
	, OnItemSelectedListener, OnTouchListener {

		ArrayList<Song> lst = new ArrayList<Song>();

		public void setList(ArrayList<Song> lst) {
			this.lst = lst;
		}

		public int getCount() {
			return lst == null ? 0 : lst.size();
		}

		public Object getItem(int position) {
			return lst.get(position);
		}

		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			if (convertView == null) {
				//				
				convertView = mInflater.inflate(R.layout.v8_star_song_list_item,
						null);
				holder = new ViewHolder();
				holder.initView(convertView, this, this);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			Song song = (Song) getItem(position);
			holder.setValues(song, position);
			
			if (SelSongsManager.G().isSongSelected(song)) {
				selectItem(convertView);
			}
			else {
				unselectItem(convertView);
			}

			return convertView;
		}

		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			// TODO Auto-generated method stub

		}
		
		public void onItemSelected(AdapterView<?> parent, View view,
				int position, long id) {
		}

		public void onNothingSelected(AdapterView<?> parent) {
			// TODO Auto-generated method stub
			
		}
		
		public void onClick(View v) {
			Object tag = v.getTag();
			if (tag instanceof Song) {
				switch (v.getId()) {
				case R.id.name:
					XVod.G().insertSong((Song) tag);
					showMyToast("点播歌曲成功");
					selectItem((View)v.getParent());
					break;
				case R.id.add:
					XVod.G().insertSong((Song) tag);
					showMyToast("点播歌曲成功");
					selectItem((View)v.getParent().getParent());
					break;
				case R.id.insert: {
					Intent i = new Intent(Const.Action.SelSongMore);
					i.putExtra(Const.Key.SONG_INFO, (Song) tag);
					startActivityForResult(i, Const.RequestCode.SEL_SONG_MORE);
					mSelSongView = (View)v.getParent().getParent();
				}
					break;

				default:
					break;
				}
			}

		}
		
		public boolean onTouch(View view, MotionEvent event) {
			switch (event.getAction()) {
			case MotionEvent.ACTION_DOWN: {
				Object tag = view.getTag();
				if (tag instanceof ViewHolder) {
					ViewHolder vh = (ViewHolder) tag;
					if (curSelView != null) {
						ViewHolder vhOld = (ViewHolder) curSelView.getTag();
						curSelView.setBackgroundDrawable(null);
						// vhOld.preImag.setSelected(false);
						//vhOld.operate.setVisibility(View.INVISIBLE);
						vhOld.name.setSelected(false);
						vhOld.order.setSelected(false);
						//vhOld.img.setBackgroundResource(R.drawable.img_normal);
					}
					curSelView = view;
					//curSelView.setBackgroundResource(R.drawable.choosing);
					// vh.preImag.setSelected(true);
					vh.operate.setVisibility(View.VISIBLE);
					vh.order.setSelected(true);
					vh.name.setSelected(true);
					//vh.img.setBackgroundResource(R.drawable.img_pressed);
					return true;
				}
			}
				break;
			default:
				break;
			}
			return false;
		}
	
	}
*/

	public class AdapterEx extends BaseAdapter implements OnTouchListener, OnClickListener {
		private boolean isBigmap;		

		public AdapterEx(boolean isBigmap) {
			this.isBigmap = isBigmap;
		}
		
		public AdapterEx() {
			this.isBigmap = false;
		}

		public int getCount() {
			int total = Math.max(0,pageManager.getTotalPage());
			if (total <= 1) {
				return total;
			}
			return total;//Integer.MAX_VALUE;// lst == null ? 0 : lst.size();
		}

		public Object getItem(int position) {
			return null;// lst.get(position);
		}

		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.v8_page_items, null);
				convertView.setLayoutParams(new Gallery.LayoutParams(
						Gallery.LayoutParams.FILL_PARENT,
						Gallery.LayoutParams.FILL_PARENT));
				holder = new ViewHolder();
				holder.initView(convertView, this, this);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			
			int total = Math.max(1,pageManager.getTotalPage());
			int page = position % total;
			ArrayList<Song> lst = readData(page);//mPageCache.get(PAGE_SIZE*position);//
			holder.setValues(lst, page);
			
			return convertView;
		}

		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			// TODO Auto-generated method stub
			if (isNeting) {
				return;
			}
		}

		public void onClick(View v) {
			Object tag = v.getTag();
			if (tag instanceof Song) {
				switch (v.getId()) {
				case R.id.name:
				case R.id.add:
					selectItem((View)v.getParent());
					XVod.G().insertSong((Song) tag);
					//showMyToast("点播歌曲成功");
					break;
//				case R.id.insert: {
//					final Player p = Player.G();
//					if (p.getPlaylistCount() < Player.MAX_SEL) {
//						int count = p.getPlaylistCount();
//						XVod.G().insertSong((Song) tag);
//						XVod.G().preSortSong(count, 1); // 1??
//					}
//				}
//					break;

				case R.id.access: {
					/*
					final Player p = Player.G();
					if (p.getPlaylistCount() < Player.MAX_SEL) {
						int count = p.getPlaylistCount();
						XVod.G().insertSong((Song) tag);
						XVod.G().preSortSong(count, 1); // 1??
					}
					*/

					Intent i = new Intent(Const.Action.SelSongMore);
					i.putExtra(Const.Key.SONG_INFO, (Song) tag);
					startActivityForResult(i, Const.RequestCode.SEL_SONG_MORE);
					mSelSongView = (View)v.getParent();
				}
				break;
				case R.id.singer: {

				}
				break;
				default:
					break;
				}
			}

		}
		
		public boolean onTouch(View v, MotionEvent event) {
			//selectItem(v);
			return false;
		}

	}

	public int getDefinionResId(Song s) {
		String def = s.getDefinition();
		if (Const.SongType.MTV.equals(def)) {
			return R.drawable.song_mtv;
		} else if (Const.SongType.CONCERT.equals(def)) {
			return R.drawable.song_concert;
		} else if (Const.SongType.HIGH.equals(def)) {
			return R.drawable.song_high;
		} else {
			return -1;
		}
	}

	class ViewHolder {

		public View root;
		// public ListView listView;
		// public SubAdapterEx subAdapterEx;
		public View[] rows = new View[PAGE_SIZE];

		public ViewHolder() {
		}

		public void initView(View layout, OnClickListener lis, OnTouchListener touch) {
			root = layout;
			rows[0] = root.findViewById(R.id.row1);
			rows[1] = root.findViewById(R.id.row2);
			rows[2] = root.findViewById(R.id.row3);
			rows[3] = root.findViewById(R.id.row4);
			rows[4] = root.findViewById(R.id.row5);
			rows[5] = root.findViewById(R.id.row6);
			rows[6] = root.findViewById(R.id.row7);

			for (int i = 0; i < rows.length; i++) {
				SubViewHolder subHolder = initSubView(rows[i], lis);
				rows[i].setTag(subHolder);
				rows[i].setOnTouchListener(touch);
			}
		}

		private SubViewHolder initSubView(View layout, OnClickListener lis) {
			SubViewHolder subHolder = new SubViewHolder();
			//subHolder.preImag = (TextView) layout.findViewById(R.id.img);
			subHolder.name = (TextView) layout.findViewById(R.id.name);
			//subHolder.singer = (TextView) layout.findViewById(R.id.singer);
			//subHolder.definion = (TextView) layout.findViewById(R.id.definition);
			//subHolder.operate = layout.findViewById(R.id.operate);
			subHolder.add = layout.findViewById(R.id.add);
			//subHolder.insert = layout.findViewById(R.id.insert);
			subHolder.access = layout.findViewById(R.id.access);
			subHolder.add.setOnClickListener(lis);
			//subHolder.insert.setOnClickListener(lis);
			subHolder.access.setOnClickListener(lis);
			
			subHolder.name.setOnClickListener(lis);
			return subHolder;
		}

		public void setValues(ArrayList<Song> lst, int pos) {
			int songSize = lst == null ? 0 : lst.size();
			for (int i = 0; i < rows.length; i++) {
				if (i < songSize) {
					rows[i].setVisibility(View.VISIBLE);
					setSubValues(lst.get(i), (SubViewHolder) rows[i].getTag(),
							pos * PAGE_SIZE + i);
					if (SelSongsManager.G().isSongSelected(lst.get(i))) {
						selectItem(rows[i]);
					}
					else {
						unselectItem(rows[i]);
					}
				} else {
					rows[i].setVisibility(View.INVISIBLE);
					setSubValues(null, (SubViewHolder) rows[i].getTag(), pos * PAGE_SIZE + i);
				}
			}
		}

		private void setSubValues(Song s, SubViewHolder holder, int pos) {
			holder.setValues(s, pos);
		}
	}

	class SubViewHolder {
		public TextView name;
		//public TextView singer;
		//public TextView definion;
		//public TextView preImag;
		//public View operate;
		public View add;
		//public View insert;
		public View access;

		public void setValues(Song data, int pos) {
			if (data == null) {
				name.setTag(data);
				add.setTag(data);
//				insert.setTag(data);
				access.setTag(data);
				name.setText(null);
				//definion.setBackgroundDrawable(null);
				//operate.setVisibility(View.INVISIBLE);
				return;
			}
			name.setText(data.getName());
			//singer.setText(data.getSingerName());
//			int def = getDefinionResId(data);
//			if (def == -1) {
//				definion.setBackgroundDrawable(null);
//			} else {
//				definion.setBackgroundResource(def);
//			}
			add.setTag(data);
//			insert.setTag(data);
			access.setTag(data);
			name.setTag(data);
		}
	}

	public void onItemSelected(AdapterView<?> parent, View view, int position,
			long id) {
		int total = Math.max(1,pageManager.getTotalPage());
		
		pageManager.setCurrentIndex(position % total, false);
	}

	public void onNothingSelected(AdapterView<?> parent) {
		// TODO Auto-generated method stub
	}
	
/*
	class ViewHolder {

		public TextView order;
		public View operate;
		public TextView name;
		//public TextView img;
		public View add;
		public View insert;
		public View root;

		// public TextView singer;

		public ViewHolder() {
		}

		public void initView(View layout, OnClickListener lis, OnTouchListener tch) {
			//img = (TextView) layout.findViewById(R.id.img);
			order = (TextView) layout.findViewById(R.id.order);
			name = (TextView) layout.findViewById(R.id.name);
			// singer = (TextView) layout.findViewById(R.id.singer);
			operate = layout.findViewById(R.id.operate);
			add = layout.findViewById(R.id.add);
			insert = layout.findViewById(R.id.insert);
			add.setOnClickListener(lis);
			insert.setOnClickListener(lis);
			root = layout;
			root.setOnTouchListener(tch);
			
			name.setOnClickListener(lis);
		}

		public void setValues(Song data, int pos) {
			if (data == null) {
				name.setTag(data);
				add.setTag(data);
				insert.setTag(data);
				root.setVisibility(View.INVISIBLE);
				return;
			}
			
			root.setVisibility(View.VISIBLE);
			int page = pageManager.getCurrentIndex();
			int index = page * PAGE_SIZE + pos + 1;
			if (index < 10) {
				order.setText("0" + index);
			} else {
				order.setText(String.valueOf(index));
			}
			name.setText(data.getName());
			// singer.setText(data.getSinger());
			add.setTag(data);
			insert.setTag(data);
			name.setTag(data);
		}
	}
*/
	public ArrayList<Song> readData(int pageIndex) {
		ArrayList<Song> lst = mPageCache.get(pageIndex * PAGE_SIZE);
		if (lst == null) {
			mSearch.loadSongData(pageIndex);
			if (mPageCache.size() > pageIndex * PAGE_SIZE) {
				lst = mPageCache.get(pageIndex * PAGE_SIZE);
			}
		}
		
		return lst;
	}
	

	long lastPageChangeTime = System.currentTimeMillis(); 
	public void onPageIndexChanged(int prePageIndex, int currentPageIndex,
			int totalPages) {
		if (System.currentTimeMillis() - lastPageChangeTime > 300) {			
			final ArrayList<Song> lst = mPageCache.get(currentPageIndex * PAGE_SIZE);
			curSongList = lst;
			refreshPage();
			listView.setSelection(currentPageIndex);
		}
		lastPageChangeTime = System.currentTimeMillis(); 
	}

	public void onPageIndexChangedError(int prePageIndex, int currentPageIndex,
			int totalPages) {
		// TODO Auto-generated method stub

	}
	
	protected void onDQManagerDisconnect() {
//		if (mSearch != null) {
//			mSearch.onDisconnect();
//		}
		
	}
	
	protected void onDQManagerReconnect() {
//		query();
	}

//	public void loadData(SongParser sp, int pageIndex) {
//		long id = XVod.G().requestRecord(sp, pageIndex * PAGE_SIZE, PAGE_SIZE);
//		pageSongReq.put(id, pageIndex);
//	}
	
	class Search implements EventsListener{
		//默认队列形式后歌星,先歌曲，
		private final static int CLOSE = 0;
		private final static int OPEN = 1;
		private final static int BUSY = 2;
		private final static int IDLE = 3;
		private String curSearch;
//		private String runningSearch;
		private DQQuery mCurSongQuery;
		private DQQuery mCurStarQuery;
		private DQQueryResult querySong;
		private DQQueryResult querySinger;
		private int state;
		private boolean autoFinish;
		private long singerId;
		
		public void search(String search) {
			curSearch = search;
			searchSinger();
//			searchSongs();
		}
		
		public void loadSongData(int pageIndex) {
			if (state == CLOSE || querySong == null) {
				return;
			}
			SongParser sp = new SongParser(querySong);
			loadSongData(sp,pageIndex);
		}
		
		public void loadSingerData(SingerParser sp) {
			state = BUSY;
			DQRead read = new DQRead(sp);
			read.setRequest(0, 1);
			singerId = XVod.G().addRequest(read);
		}
		
		public void loadSongData(SongParser sp, int pageIndex) {
			
			state = BUSY;
			DQRead read = new DQRead(sp);
			read.setRequest(pageIndex * PAGE_SIZE, PAGE_SIZE);
			long id = XVod.G().addRequest(read);
			pageSongReq.put(id, pageIndex);
		}

		public void regesiterEventsListener() {
			XVod.G().registerListener(EventsManager.Event.QUERY_RESPONSE, this);
			XVod.G().registerListener(EventsManager.Event.QUERY_RECORDS, this);
			XVod.G().registerListener(EventsManager.Event.QUERY_CLOSE, this);
			XVod.G().registerListener(EventsManager.Event.DISCONNECT, this);
			XVod.G().registerListener(EventsManager.Event.SELECT_SONG_RESULT, this);
		}
		
		public void unRegisterEventsListener() {
//			if (state == OPEN || state == BUSY) {
//				autoFinish = true;
//			} else if (state == IDLE){
//				closeSnap();
//			} else {
//				removeRegisterEventsListener();
//			}
			
//			if (state == OPEN) {
			autoFinish = true;
			if (mCurStarQuery != null && mCurStarQuery.getState() != Request.STATE_RESPONSED) {
				mCurStarQuery.setToClose();
			}
			if (mCurSongQuery != null && mCurSongQuery.getState() != Request.STATE_RESPONSED) {
				mCurSongQuery.setToClose();
			}
//			} 
//			else if (state == IDLE || state == BUSY){
			closeSnap();
			removeRegisterEventsListener();
//			} else {
//				removeRegisterEventsListener();
//			}
		}
		
		public void onEvent(int event, Object obj, boolean isSuc) {
			switch (event) {
			case EventsManager.Event.SELECT_SONG_RESULT:
				String str = (String)obj;
				if (str.equals("0")) {
					showMyToast("点播歌曲成功");
				}
				else if (str.equals("-1")) {
					showMyToast("歌曲已在‘已选’列表中");
				} 
				else {
					showMyToast("点播歌曲失败，请重试");
				}
				break;
			case EventsManager.Event.QUERY_RESPONSE: {
				DQQueryResult res = (DQQueryResult) obj;
				if (isSuc) {
					 if (mCurStarQuery != null
								&& mCurStarQuery.getId() == res.getId()) {
							querySinger = (DQQueryResult) obj;
							if (!autoFinish) {
								SingerParser sp1 = new SingerParser(querySinger,
										true);
								loadSingerData(sp1);
							} else {
								closeSnap();
							}
						}  else	if (mCurSongQuery != null
							&& mCurSongQuery.getId() == res.getId()) {
						querySong = (DQQueryResult) obj;
						pageSongReq.clear();
						int total = querySong.getRecordTotal();
						int pageCount = ( total > 0 ? total- 1: 0)
								/ PAGE_SIZE + 1;
						pageManager.setPageInfo(pageManager.getCurrentIndex(),
								pageCount, false);
						if (!autoFinish) {
							SongParser sp = new SongParser(querySong);
							loadSongData(sp, pageManager.getCurrentIndex());
						} else {
							closeSnap();
						}
					}
				} else {
					// Toast
					// 忽略这次查询,另起一次查询
					if (querySong != null) {
						final DQQueryResult q = querySong;
						querySong = null;
						XVod.G().addRequest(new DQClose(q.getSnap()));
					}
					pageSongReq.clear();
					mPageCache.clear();
					pageManager.setPageInfo(1, 1, true);
					refreshPage();
				}
			}
				break;
			case EventsManager.Event.QUERY_RECORDS: {
				DQReadResult result = (DQReadResult) obj;
				if (isSuc && obj != null) {
					long id = result.getId();
					if (singerId == id) {
						DQSinger singers = (DQSinger) obj;
						ArrayList<Singer> lst = singers.getList();
						if (lst != null && !lst.isEmpty()) {
							mSinger = lst.get(0);
							if (!isFinishing() && !autoFinish) {
								refreshSingerInfo();
							}
						}
						if (autoFinish) {
							closeSnap();
						} else {
							searchSongs();
						}
					} else {
						Integer pg = pageSongReq.get(id);
						if (pg != null) {
							DQSongs songs = (DQSongs) obj;
							if (Util.VLOG) {
								ArrayList<Song> songlstArrayList = songs.getList();
								StringBuilder sBuilder = new StringBuilder();
								for (int i = 0; i < songlstArrayList.size(); i++) {
									sBuilder.append(songlstArrayList.get(i).getName());
									sBuilder.append(',');
								}
								VODLog.e("StarSongsActivity", "onEvent(). singerId != id. song list = " + sBuilder.toString());
							}
							mPageCache.put(songs.getBegin(), songs.getList());
							// if (pageManager.getCurrentIndex() * PAGE_SIZE ==
							// songs
							// .getBegin()) {
							curSongList = songs.getList();
							if (!isFinishing() && !autoFinish) {
								refreshPage();
							}
							if (autoFinish) {
								closeSnap();
							} else {
								state = IDLE;
							}
						}
					}
				} 
				// else if fail or obj is null
			}
				break;
			case EventsManager.Event.QUERY_CLOSE: {
				if (isSuc && obj instanceof Byte) {
					int snap = (Byte) obj;
					if (querySinger != null && querySong == null && querySinger.getSnap() == snap) {
						state = CLOSE;
						removeRegisterEventsListener();
					}
					if (querySong != null && querySong.getSnap() == snap) {
						state = CLOSE;
//						if (autoFinish) {
						removeRegisterEventsListener();
//						}
					}
				}
			}
				break;
			case EventsManager.Event.DISCONNECT: {
				if (obj != null && obj instanceof Integer) {
					int id = (Integer) obj;
					if (id == NetManager.G().getDQManagerId()) {
						onDisconnect();
					}
				}
			}
				break;

			default:
				break;
			}
		}
		
		private void searchSinger() {
			mCurStarQuery = new DQQuery(DQQuery.TABLE_STAR, DQQuery
					.createEquName(curSearch));
			XVod.G().addRequest(mCurStarQuery);
			state = OPEN;
		}
		
		private void searchSongs() {
//			if (mQueryType == QueryType.COMMON) {
//				mCurSongQuery = new DQQuery(DQQuery.TABLE_SONG, DQQuery.getSongsEquStarName(curSearch));
//			} else 
			{
				mCurSongQuery = new DQQuery(DQQuery.TABLE_SONG, DQQuery.getSongsContainStarName(curSearch));
			}
			XVod.G().addRequest(mCurSongQuery);
			state = OPEN;
		}
		
		//搜索指定的歌名
		private void searchSpecifiedSongs(String name) {
			String queryString = DQQuery.getSpecifiedSongsEquStarName(curSearch, name);
			mCurSongQuery = new DQQuery(DQQuery.TABLE_SONG, queryString);
			XVod.G().addRequest(mCurSongQuery);
			state = OPEN;
		}

		//开放给搜索用
		public void searchSongs(String songName) {
			//清除原先的显示
			 if (querySong != null) {
				 final DQQueryResult q = querySong;
				 querySong = null;
				 XVod.G().addRequest(new DQClose(q.getSnap()));
				 pageSongReq.clear();
				 mPageCache.clear();
			 }
			 
			 pageManager.setCurrentIndex(0, true);
			
			//搜索
			if (songName != null && songName.length() > 0) {
				 searchSpecifiedSongs(songName);
			} else {
				searchSongs();
			}
		}
		
		private void removeRegisterEventsListener() {
			XVod.G().unRegisterListener(EventsManager.Event.QUERY_RECORDS, this);
			XVod.G().unRegisterListener(EventsManager.Event.QUERY_RESPONSE, this);
			XVod.G().unRegisterListener(EventsManager.Event.QUERY_CLOSE, this);
			XVod.G().unRegisterListener(EventsManager.Event.DISCONNECT, this);
			XVod.G().unRegisterListener(EventsManager.Event.SELECT_SONG_RESULT, this);
		}
		
		private void closeSnap() {
			state = BUSY;
//			if (querySinger != null && mCurStarQuery != null && !mCurStarQuery.isSetToClose()) {
//				XVod.G().addRequest(new DQClose(querySinger.getSnap()));
//			}
			
			Log.e("StarSongs:", "snap:mCurStarQuery:" + mCurStarQuery);
			
			if (mCurStarQuery != null) {
				Log.e("StarSongsActivity", "snap: mCurStarQuery issetClose:" + mCurStarQuery.isSetToClose());
			}
			
			if (mCurStarQuery != null && !mCurStarQuery.isSetToClose()) {
				XVod.G().addRequest(new DQClose(mCurStarQuery.getSnap()));
			}
			
			
			Log.e("StarSongs:", "snap:mCurSongQuery:" + mCurSongQuery);
			
			if (mCurSongQuery != null) {
				Log.e("StarSongsActivity", "snap: issetClose:" + mCurSongQuery.isSetToClose());
			}
//			if (querySong != null && mCurSongQuery != null && !mCurSongQuery.isSetToClose()) {
//				XVod.G().addRequest(new DQClose(querySong.getSnap()));
//			}
			
			if (mCurSongQuery != null && !mCurSongQuery.isSetToClose()) {
				XVod.G().addRequest(new DQClose(mCurSongQuery.getSnap()));
			}
		}
		
		public void onDisconnect() {
			state = CLOSE;
		}
	}

	@Override
	public void onSwitched(View view, int position) {
		// TODO Auto-generated method stub

		mHandle.removeMessages(1);
		mHandle.sendEmptyMessageDelayed(1, 5);
	}
	

	private float oldX;
	private final float diff = 5;
	private Rect rect = new Rect();
	@Override
	public void onMyTouchListner(float x, float y, int e) {
		// TODO Auto-generated method stub
		/*
		if (e == HListView.MyTouchListner.EVENT_DOWN) {
			oldX = x;
			return;
		} 
		else if (e == HListView.MyTouchListner.EVENT_UP 
				|| e == HListView.MyTouchListner.EVENT_CANCEL) {
			if (Math.abs(oldX - x) < diff) {
			}
			if (e == HListView.MyTouchListner.EVENT_UP) {
				mHandle.removeMessages(1);
				mHandle.sendEmptyMessageDelayed(1, 200);
			}
		}
		*/
	}
	private Handler mHandle = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			int total = Math.max(1,pageManager.getTotalPage());
			int position = listView.getSelectedItemPosition();

			pageManager.setCurrentIndex(position % total, false);
			if (position >= 0) {
				if (curPageView != null) {
					//curPageView.setText(String.valueOf(position % total + 1));
					//totalPageView.setText(String.valueOf(total));
					curPageView.setText(getString(R.string.cur_page, position % total + 1));
					totalPageView.setText(getString(R.string.total_page, total));
				}
			}
		}
		
	};

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		// TODO Auto-generated method stub
		
	}

	long currentTime = System.currentTimeMillis(); 
	@Override
	public void afterTextChanged(Editable s) {
		// TODO Auto-generated method stub
		mSearchHandler.removeMessages(0);

		String search = s.toString();
		if (search.trim().equals("")) {
			mSearchWord = null;
		}
		else {
			mSearchWord = search;
		}
		
  	  	mSearchHandler.sendEmptyMessageDelayed(0, 500);
		currentTime = System.currentTimeMillis(); 
	}

	String mSearchWord = "";
	String mLastSearchWord = "";
	
	//定义Handler对象
	private Handler mSearchHandler = new Handler(){
	   @Override
	   //当有消息发送出来的时候就执行Handler的这个方法
	   public void handleMessage(Message msg){
	      super.handleMessage(msg);
	      try {
	    	  mSearchHandler.removeMessages(0);
	    	  if (mSearchWord != mLastSearchWord) {
	    		  mSearch.searchSongs(mSearchWord);
		    	  mLastSearchWord = mSearchWord;
	    	  }
	      }
	      catch(Exception e)
	      {
	    	  
	      }
	   }
	};
}
